﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Windows.Forms;
using Aspose.Words;
using Aspose.Words.Tables;
using DevComponents.AdvTree;
using KnowledgeNotebook.BaseClass;
using KnowledgeNotebook.DAL;
using KnowledgeNotebook.Forms;
using KnowledgeNotebook.Properties;
using Node = DevComponents.AdvTree.Node;

namespace KnowledgeNotebook
{
    public partial class frmMain : Form
    {
        public static frmMain MainForm;
        public string Database;

        private Node _node;
        private string _table;
        public string TableName
        {
            get { return _table; }
        }

        public frmMain()
        {
            InitializeComponent();
            MainForm = this;
            Database = String.Empty;
            _table = String.Empty;
            _node = null;
            contextMenu.ItemClicked += contextMenu_ItemClicked;
        }


        private void SetSearchSapConnectString()
        {
            if (DatabaseOptionBaseClass.IsTrustConnect)
            {
                DatabaseOptionBaseClass.ConnectString =
                    "Data Source=" + DatabaseOptionBaseClass.Server + ";Initial Catalog=SAP;Integrated Security=true";
            }
            else
            {
                DatabaseOptionBaseClass.ConnectString =
                    "Data Source=" + DatabaseOptionBaseClass.Server +
                    ";Initial Catalog=SAP;Persist Security Info=True;User ID=" +
                    DatabaseOptionBaseClass.UserName +
                    ";Password=" + DatabaseOptionBaseClass.Password;
            }

            Database = "SAP";
            comboSchema.Text = "SAP";
            LoadDatabase();
        }


        private void btnToolbarAdd_Click(object sender, EventArgs e)
        {
            using (frmAddOrUpdate frmDetail = new frmAddOrUpdate())
            {
                frmDetail.ShowDialog();
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }


        private void LoadDatabase()
        {
            nodeDatabase.Text = Database;
            DatabaseOption dbo = new DatabaseOption();
            nodeTable.Nodes.Clear();
            List<string> tables = dbo.GetTables(Database);
            if (tables != null)
            {
                foreach (string table in tables)
                {
                    Node node = new Node(table);
                    node.Image = Resources.table;
                    nodeTable.Nodes.Add(node);
                    node.NodeDoubleClick += node_NodeDoubleClick;
                }
                nodeTable.Expand();
            }
        }


        private void frmMain_Load(object sender, EventArgs e)
        {
            LoadDatabase();

            DatabaseOption dbo = new DatabaseOption();
            dbo.GetKeywords();
            sqlEditor.Document.LoadLanguageFromXml(Application.StartupPath + "\\ActiproSoftware.SQL.xml", 0);
        }


        private void node_NodeDoubleClick(object sender, EventArgs e)
        {
            // DatabaseOption dbo = new DatabaseOption();
            ((Node) sender).Nodes.Clear();
            Node nodefield = new Node("字段");
            nodefield.Image = Resources.Fields;
            ((Node) sender).Nodes.Add(nodefield);
            nodefield.NodeDoubleClick += nodefield_NodeDoubleClick;
            nodefield_NodeDoubleClick(nodefield, null);
            ((Node) sender).Expand();
            Node nodeKey = new Node("键");
            nodeKey.Image = Resources.Key;
            ((Node) sender).Nodes.Add(nodeKey);
            nodeKey.NodeDoubleClick += nodeKey_NodeDoubleClick;


            Node nodeIndex = new Node("索引");
            nodeIndex.Image = Resources.Index;
            ((Node) sender).Nodes.Add(nodeIndex);
            nodeIndex.NodeDoubleClick += nodeIndex_NodeDoubleClick;


            Node nodeConstraints = new Node("约束");
            nodeConstraints.Image = Resources.Constraints;
            ((Node) sender).Nodes.Add(nodeConstraints);
            nodeConstraints.NodeDoubleClick += nodeConstraints_NodeDoubleClick;


            Node nodeTriggers = new Node("触发器");
            nodeTriggers.Image = Resources.Triggers;
            ((Node) sender).Nodes.Add(nodeTriggers);
            nodeTriggers.NodeDoubleClick += nodeTriggers_NodeDoubleClick;
        }

        private void nodefield_NodeDoubleClick(object sender, EventArgs e)
        {
            DatabaseOption dbo = new DatabaseOption();
            List<string> fields = dbo.GetFields(((Node) sender).Parent.Text);
            ((Node) sender).Nodes.Clear();
            if (fields != null)
            {
                foreach (string field in fields)
                {
                    Node node = new Node(field);
                    node.Image = Resources.Fields;
                    ((Node) sender).Nodes.Add(node);
                }
            }
            ((Node) sender).Expand();
        }

        private void nodeTriggers_NodeDoubleClick(object sender, EventArgs e)
        {
            DatabaseOption dbo = new DatabaseOption();
            List<string> triggers = dbo.GetTriggers(((Node) sender).Parent.Text);
            ((Node) sender).Nodes.Clear();
            if (triggers != null)
            {
                foreach (string trigger in triggers)
                {
                    Node node = new Node(trigger);
                    node.Image = Resources.Triggers;
                    ((Node) sender).Nodes.Add(node);
                }

                ((Node) sender).Expand();
            }
        }

        private void nodeConstraints_NodeDoubleClick(object sender, EventArgs e)
        {
            DatabaseOption dbo = new DatabaseOption();
            List<string> constraints = dbo.GetConstraints(((Node) sender).Parent.Text);
            ((Node) sender).Nodes.Clear();
            if (constraints != null)
            {
                foreach (string constraint in constraints)
                {
                    Node node = new Node(constraint);
                    node.Image = Resources.Constraints;
                    ((Node) sender).Nodes.Add(node);
                }

                ((Node) sender).Expand();
            }
        }

        private void nodeKey_NodeDoubleClick(object sender, EventArgs e)
        {
            DatabaseOption dbo = new DatabaseOption();
            List<string> keys = dbo.GetKeys(((Node) sender).Parent.Text);
            ((Node) sender).Nodes.Clear();
            if (keys != null)
            {
                foreach (string key in keys)
                {
                    Node node = new Node(key);
                    if (key.Contains("PK"))
                    {
                        node.Image = Resources.Key;
                    }
                    else
                    {
                        node.Image = Resources.ForeignKey;
                    }
                    ((Node) sender).Nodes.Add(node);
                }

                ((Node) sender).Expand();
            }
        }

        private void nodeIndex_NodeDoubleClick(object sender, EventArgs e)
        {
            DatabaseOption dbo = new DatabaseOption();
            List<string> indexes = dbo.GetIndexes(((Node) sender).Parent.Text);
            ((Node) sender).Nodes.Clear();
            if (indexes != null)
            {
                foreach (string index in indexes)
                {
                    Node node = new Node(index);
                    node.Image = Resources.Index;
                    ((Node) sender).Nodes.Add(node);
                }

                ((Node) sender).Expand();
            }
        }

        private void SearchData()
        {
            SetSearchSapConnectString();

            DatabaseOption dbo = new DatabaseOption();
            DataTable dt = dbo.SearchData(txtTitle.Text);

            dataGrid.DataSource = dt;

            if (dataGrid.RowCount > 0)
            {
                dataGrid.Columns[1].HeaderText = "搜索结果";
                dataGrid.Columns[1].Width = dataGrid.Width;
                dataGrid.Columns[0].Visible = false;
                dataGrid.Columns[2].Visible = false;
            }
            superTabControl1.SelectedTabIndex = 0;
        }


        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchData();
        }


        private void ShowSearchResult()
        {
            using (frmAddOrUpdate frmAddOrUpdate = new frmAddOrUpdate())
            {
                if (dataGrid.RowCount > 0 && dataGrid.CurrentRow != null)
                {
                    frmAddOrUpdate.AddForm.Id = Convert.ToInt32(dataGrid.CurrentRow.Cells[0].Value);
                    frmAddOrUpdate.AddForm.Title = dataGrid.CurrentRow.Cells[1].Value.ToString();
                    frmAddOrUpdate.AddForm.Detail = dataGrid.CurrentRow.Cells[2].Value.ToString();

                    // BindData=new Binding("Rtf",dataGrid.DataSource,"Detail",true);
                }

                frmAddOrUpdate.ShowDialog();
            }
        }

        private void dataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            ShowSearchResult();
        }

        private void DeleteMultiData(string tablename, string fieldname)
        {
            string temp = "(";
            if (dataGrid.RowCount > 0 && dataGrid.SelectedRows.Count > 0)
            {
                DatabaseOption dbo = new DatabaseOption();
                for (int i = 0; i < dataGrid.SelectedRows.Count - 1; i++)
                {
                    int id = Convert.ToInt32(dataGrid.SelectedRows[i].Cells[0].Value);
                    temp = temp + id + ",";
                }
                temp += dataGrid.SelectedRows[dataGrid.SelectedRows.Count - 1].Cells[0].Value + ")";

                string sql = "delete from " + tablename + " where " + fieldname + " in " + temp;

                if (DialogResult.Yes ==
                    MessageBox.Show(Resources.ConfirmDelete, Resources.ConfirmTitle, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question))
                {
                    dbo.DeleteMultiData(sql);
                    SearchData();
                }
            }
            else
            {
                Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, "请先从列表中选中至少一行。");
            }
        }

        private void btnToolbarDelete_Click(object sender, EventArgs e)
        {
            DeleteMultiData("SAP_Knowledge", "ID");
        }


        private void btnClear_Click(object sender, EventArgs e)
        {
            txtTitle.Clear();
        }

        private void nodeProcedure_NodeDoubleClick(object sender, EventArgs e)
        {
            DatabaseOption dbo = new DatabaseOption();
            List<string> procedures = dbo.GetProcedures(Database);
            nodeProcedure.Nodes.Clear();
            if (procedures != null)
            {
                foreach (string procedure in procedures)
                {
                    Node node = new Node(procedure);
                    node.Image = Resources.Procedure;
                    nodeProcedure.Nodes.Add(node);
                    node.NodeDoubleClick += nodeProcedurePara_NodeDoubleClick;
                }

                nodeProcedure.Expand();
            }
        }

        private void nodeProcedurePara_NodeDoubleClick(object sender, EventArgs e)
        {
            DatabaseOption dbo = new DatabaseOption();
            List<string> paras = dbo.GetProcParameters(((Node) sender).Text);
            ((Node) sender).Nodes.Clear();
            if (paras != null)
            {
                foreach (string para in paras)
                {
                    Node node = new Node(para);
                    node.Image = Resources.Parameters;
                    ((Node) sender).Nodes.Add(node);
                }

                ((Node) sender).Expand();
            }
        }

        private void nodeView_NodeDoubleClick(object sender, EventArgs e)
        {
            DatabaseOption dbo = new DatabaseOption();
            List<string> views = dbo.GetViews(Database);
            nodeView.Nodes.Clear();
            if (views != null)
            {
                foreach (string view in views)
                {
                    Node node = new Node(view);
                    node.Image = Resources.View;
                    nodeView.Nodes.Add(node);
                }

                nodeView.Expand();
            }
        }


        private void btnExecute_Click(object sender, EventArgs e)
        {
            if (sqlEditor.Text != String.Empty)
            {
                DatabaseOption dbo = new DatabaseOption();
                dbo.GetCustomQueryData(txtResult, tabQuery, sqlEditor.Text);
            }
            else
            {
                Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, "SQL语句不能为空！");
            }
        }


        private void timer_Tick(object sender, EventArgs e)
        {
            progressbar.Enabled = true;
            progressbar.Visible = true;

            progressbar.Value += 1;
            if (progressbar.Value >= 100)
            {
                progressbar.Value = 0;
            }
        }


        private void comboSchema_SelectedIndexChanged(object sender, EventArgs e)
        {
            Database = comboSchema.Text;

            if (DatabaseOptionBaseClass.IsTrustConnect)
            {
                DatabaseOptionBaseClass.ConnectString = "Data Source=" + DatabaseOptionBaseClass.Server +
                                                        ";Initial Catalog=" + comboSchema.Text +
                                                        ";Integrated Security=true";
            }
            else
            {
                DatabaseOptionBaseClass.ConnectString = "Data Source=" + DatabaseOptionBaseClass.Server +
                                                        ";Initial Catalog=" + comboSchema.Text +
                                                        ";Persist Security Info=True;User ID=" +
                                                        DatabaseOptionBaseClass.UserName + ";Password=" +
                                                        DatabaseOptionBaseClass.Password;
            }

            LoadDatabase();
            nodeProcedure.Nodes.Clear();
            nodeView.Nodes.Clear();
            nodeSchemas.Nodes.Clear();
        }

        private void nodeSchemas_NodeDoubleClick(object sender, EventArgs e)
        {
            DatabaseOption dbo = new DatabaseOption();
            List<string> schemas = dbo.GetSchemas(Database);
            nodeSchemas.Nodes.Clear();
            if (schemas != null)
            {
                foreach (string schema in schemas)
                {
                    Node node = new Node(schema);
                    node.Image = Resources.Schemas;
                    nodeSchemas.Nodes.Add(node);
                }

                nodeSchemas.Expand();
            }
        }


        private void comboSchema_Click(object sender, EventArgs e)
        {
            List<string> schemas;
            DatabaseOption dbo = new DatabaseOption();
            timer.Enabled = true;
            progressbar.Visible = true;
            ThreadPool.QueueUserWorkItem(
                delegate
                    {
                        schemas = dbo.ChangeSchemas();
                        try
                        {
                            BeginInvoke(
                                (MethodInvoker)
                                delegate
                                    {
                                        if (schemas != null)
                                        {
                                            comboSchema.Items.Clear();

                                            comboSchema.Items.AddRange(schemas.ToArray());
                                            //  comboSchema.SelectedIndex = 0;
                                        }

                                        timer.Enabled = false;
                                        progressbar.Visible = false;
                                        progressbar.Enabled = false;
                                    });
                        }
                        catch (Exception ex)
                        {
                            Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, ex.Message);
                        }
                    });
        }


        private void btnToolbarAbout_Click(object sender, EventArgs e)
        {
            ShowAboutForm();
        }

        private void menuAbout_Click(object sender, EventArgs e)
        {
            ShowAboutForm();
        }


        private static void ShowAboutForm()
        {
            using (frmAbout about = new frmAbout())
            {
                about.ShowDialog();
            }
        }

        private void dataGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    dataGrid.ClearSelection();
                    if (dataGrid.CurrentRow != null) dataGrid.CurrentRow.Selected = false;
                    dataGrid.Rows[e.RowIndex].Selected = true;
                    dataGrid.CurrentCell = dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    contextMenu.Items.Clear();
                    contextMenu.Items.Add("查看详细");
                    contextMenu.Items.Add("删除这条记录", Resources.Cancel);
                    contextMenu.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        private void contextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text)
            {
                case "查看详细":
                    ((ContextMenuStrip) sender).Hide();
                    ShowSearchResult();
                    //   ((ContextMenuStrip) sender).ItemClicked -= contextMenu_ItemClicked;
                    break;
                case "删除这条记录":
                    ((ContextMenuStrip) sender).Hide();
                    if (dataGrid.CurrentRow != null)
                    {
                        int index = Convert.ToInt32(dataGrid.CurrentRow.Cells[0].Value);
                        DeleteSelectedSearchRow(index);
                    }
                    else
                    {
                        Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, "删除失败");
                    }

                    //     ((ContextMenuStrip)sender).ItemClicked -= contextMenu_ItemClicked;
                    break;
                case "选择前100项":
                    ((ContextMenuStrip) sender).Hide();
                    SelectTop100(_table);
                    break;
                case "选择所有项":
                    ((ContextMenuStrip) sender).Hide();
                    SelectAll(_table);
                    break;
                case "展开":
                    ((ContextMenuStrip) sender).Hide();
                    ExpandNode(_node);
                    break;
                case "折叠":
                    ((ContextMenuStrip) sender).Hide();
                    CollapseNode(_node);
                    break;
                case "清空表":
                    ((ContextMenuStrip) sender).Hide();
                    ClearTable(_table);
                    break;
                case "删除表":
                    ((ContextMenuStrip) sender).Hide();
                    DeleteTable(_table);
                    break;
                case "数据导出Word":
                    ((ContextMenuStrip) sender).Hide();
                    frmExportSetting exportsetting=new frmExportSetting();
                    if (System.Windows.Forms.DialogResult.OK==exportsetting.ShowDialog())
                    {
                        DatabaseOption dbo = new DatabaseOption();
                        DataTable dt = dbo.GetQueryResult("select * from " + _table);
                        Export export = new Export();
                        export.ExportWord(_table, dt);                        
                    }
                    break;
            }
        }

        private void DeleteSelectedSearchRow(int id)
        {
            if (DialogResult.Yes ==
                MessageBox.Show("是否确认删除选中项？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                DatabaseOption dbo = new DatabaseOption();
                dbo.DeleteData(id);
                SearchData();
            }
        }

        private void SelectTop100(string table)
        {
            superTabControl1.SelectedTabIndex = 1;
            sqlEditor.Text = string.Format("select top(100) * from {0}", table);
            DatabaseOption dbo = new DatabaseOption();
            dbo.GetCustomQueryData(txtResult, tabQuery, sqlEditor.Text);
        }

        private void SelectAll(string table)
        {
            superTabControl1.SelectedTabIndex = 1;
            sqlEditor.Text = string.Format("select * from {0}", table);
            DatabaseOption db = new DatabaseOption();
            db.GetCustomQueryData(txtResult, tabQuery, sqlEditor.Text);
        }

        private void ClearTable(string table)
        {
            if (DialogResult.Yes ==
                MessageBox.Show(string.Format("清空表将会删除表中的所有数据和日志文件，是否确认继续清空{0}？", table), Resources.WarningCaption,
                                MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                superTabControl1.SelectedTabIndex = 1;
                sqlEditor.Text = string.Format("delete from {0}", table);
                DatabaseOption dbo = new DatabaseOption();
                dbo.GetCustomQueryData(txtResult, tabQuery, sqlEditor.Text);
            }
        }

        private void DeleteTable(string table)
        {
            if (DialogResult.Yes ==
                MessageBox.Show(string.Format("删除表将会从数据库中彻底删除该表，是否确认继续删除{0}？", table), Resources.WarningCaption,
                                MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                superTabControl1.SelectedTabIndex = 1;
                sqlEditor.Text = string.Format("drop table {0}", table);
                DatabaseOption dbo = new DatabaseOption();
                dbo.GetCustomQueryData(txtResult, tabQuery, sqlEditor.Text);
            }
        }

        private void ExpandNode(Node node)
        {
            nodeTable.Expand();
            if (node.Parent != null && node.Parent != nodeDatabase)
            {
                switch (node.Parent.Text)
                {
                    case "表":
                        node_NodeDoubleClick(node, null);
                        break;
                    case "存储过程":
                        nodeProcedurePara_NodeDoubleClick(node, null);
                        break;
                    default:
                        if (node.Parent.Parent != null)
                        {
                            if (node.Parent.Parent.Text == "表")
                            {
                                switch (node.Text)
                                {
                                    case "字段":
                                        nodefield_NodeDoubleClick(node, null);
                                        break;
                                    case "索引":
                                        nodeIndex_NodeDoubleClick(node, null);
                                        break;
                                    case "键":
                                        nodeKey_NodeDoubleClick(node, null);
                                        break;
                                    case "触发器":
                                        nodeTriggers_NodeDoubleClick(node, null);
                                        break;
                                    case "约束":
                                        nodeConstraints_NodeDoubleClick(node, null);
                                        break;
                                }
                            }
                        }
                        break;
                }
            }
            else
            {
                switch (node.Text)
                {
                    case "存储过程":
                        nodeProcedure_NodeDoubleClick(node, null);
                        break;
                    case "模式":
                        nodeSchemas_NodeDoubleClick(node, null);
                        break;
                    case "视图":
                        nodeView_NodeDoubleClick(node, null);
                        break;
                }
            }
        }


        private void CollapseNode(Node node)
        {
            if (node.Expanded)
            {
                node.Collapse();
            }
        }


        private void btnToolbarUpdate_Click(object sender, EventArgs e)
        {
            if (dataGrid.Rows.Count > 0 && dataGrid.SelectedRows.Count == 1 && dataGrid.CurrentRow != null)
            {
                using (frmAddOrUpdate addOrUpdate = new frmAddOrUpdate())
                {
                    frmAddOrUpdate.AddForm.Id = Convert.ToInt32(dataGrid.CurrentRow.Cells[0].Value);
                    frmAddOrUpdate.AddForm.Title = dataGrid.CurrentRow.Cells[1].Value.ToString();
                    frmAddOrUpdate.AddForm.Detail = dataGrid.CurrentRow.Cells[2].Value.ToString();
                    addOrUpdate.ShowDialog();
                }
            }
            else
            {
                Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, "请选从搜索结果中选择一行。只能选择一行进行更新操作。");
            }
        }

        private void treeObject_NodeMouseDown(object sender, TreeNodeMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //if (e.Node.Parent==nodeTable)
                //{
                _node = e.Node;
                //}
                if (_node.Parent != null)
                {
                    switch (e.Node.Parent.Text)
                    {
                        case "表":
                            _table = e.Node.Text;
                            contextMenu.Items.Clear();
                            contextMenu.Items.Add("展开", Resources.Expand);
                            contextMenu.Items.Add("折叠", Resources.Collapse);
                            contextMenu.Items.Add("选择前100项", Resources.Select);
                            contextMenu.Items.Add("选择所有项", Resources.Select);
                            contextMenu.Items.Add("数据导出Excel", Resources.Excel);

                            contextMenu.Items.Add("数据导出Word", Resources.Word);
                            contextMenu.Items.Add("数据导出PDF", Resources.Pdf);
                            contextMenu.Items.Add("清空表", Resources.TableDelete);
                            contextMenu.Items.Add("删除表", Resources.Cancel);
                            contextMenu.Show(MousePosition.X, MousePosition.Y);
                            break;
                        case "存储过程":
                            contextMenu.Items.Clear();
                            contextMenu.Items.Add("展开", Resources.Expand);
                            contextMenu.Items.Add("折叠", Resources.Collapse);
                            contextMenu.Items.Add("执行");
                            contextMenu.Items.Add("删除", Resources.Cancel);
                            contextMenu.Show(MousePosition.X, MousePosition.Y);
                            break;

                        default:
                            if (e.Node.Parent.Text != "字段" && e.Node.Parent.Text != "键" && e.Node.Parent.Text != "约束" &&
                                e.Node.Parent.Text != "索引" && e.Node.Parent.Text != "触发器" && e.Node.Parent.Text != "模式" &&
                                e.Node.Parent.Text != "视图")
                            {
                                contextMenu.Items.Clear();
                                contextMenu.Items.Add("展开", Resources.Expand);
                                contextMenu.Items.Add("折叠", Resources.Collapse);
                                contextMenu.Show(MousePosition.X, MousePosition.Y);
                            }
                            if ((e.Node.Parent.Parent != null && e.Node.Parent.Parent.Text == "存储过程"))
                            {
                                contextMenu.Items.Clear();
                                contextMenu.Hide();
                            }
                            break;
                    }
                }
            }
        }

        private void btnToolbarExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }

    internal class Export
    {
        public void ExportWord(string tablename, DataTable data)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = tablename;
            saveFileDialog.Filter = "Word 2003格式|*.doc|Word 2007格式|*.docx";
            saveFileDialog.Title = "导出Word";

            //int count = 0;

            if (DialogResult.OK == saveFileDialog.ShowDialog())
            {
                //Document doc = new Document(@"C:\Users\liangxiaorui\Desktop\MailMerge.ExecuteDataTable.doc");
                Document doc = new Document();
                DocumentBuilder builder = new DocumentBuilder(doc);

                builder.StartTable();
                // builder.PageSetup.PageWidth

                for (int i = 0; i < data.Columns.Count; i++)
                {
                    builder.InsertCell();
                    builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                    builder.Write(data.Columns[i].ColumnName);
                }
                builder.EndRow();

                for (int i = 0; i < data.Rows.Count; i++)
                {
                    for (int j = 0; j < data.Columns.Count; j++)
                    {
                        builder.InsertCell();
                        // builder.CellFormat.Orientation = TextOrientation.Horizontal;
                        builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                        builder.Write(data.Rows[i][j].ToString());
                    }
                    builder.EndRow();
                }

                // table.
                builder.EndTable();

                doc.Save(saveFileDialog.FileName);
            }
        }
    }
}